

/*
You are given the following array of stock prices (which are numbers) 
where the i-th element represents the stock price on day i:

116,68,128,7,49,20,139,65,74,18,121,70,96,178,185,28,179,123

Determine the maximum possible profit you can earn using as many transactions as you'd like. 
A transaction is defined as buying and then selling one share of the stock. 
Note that you cannot engage in multiple transactions at once. 
In other words, you must sell the stock before you buy it again.
If no profit can be made, then the answer should be 0

*/

const stock_sample = [116,68,128,7,49,20,139,65,74,18,121,70,96,178,185,28,179,123];

var list_sample_profit = [];// {sample:[],profit:...}

// 1. 穷举法:列出所有可能的操作: (包括不合法的操作)
// 只考虑买和卖, 不考虑不作为的情况 1:买  -1:卖
function calculate_sample(arr)
{
    // 存货,
    let storage = 0;// you must sell the stock before you buy it again 持仓数不能超过1
    for(let i=0;i<arr.length;++i)
    {
        let number = arr[i];
        storage+=number;
        if(storage<0 || storage==2)
        {
            return;// 这个样本不行.
            break;
        }
    }
    // console.log("可行的样本:",arr);
    let profit = 0;// 利润
    for(let i=0;i<arr.length;++i)
    {
        profit+=arr[i]*(-stock_sample[i]);
    }
    // console.log("\t\t利润:",profit);
    list_sample_profit.push({sample:arr,profit:profit});
}

function recursion_get_sample(arr , zero_or_one)
{
    arr.push(zero_or_one);
    // console.log("#10 ",arr);
    if(arr.length == stock_sample.length)
    {
        // console.log("sample:",arr);
        calculate_sample(arr);
    }
    else
    {
        recursion_get_sample(arr.slice(),-1);
        recursion_get_sample(arr.slice(),0);
        recursion_get_sample(arr.slice(),1);
    }
}


recursion_get_sample([],1);
recursion_get_sample([],0);

// 取最大值:
let most_high_value = 0;
let best_sample = [];
for(let i=0;i<list_sample_profit.length;++i)
{
    let obj = list_sample_profit[i];
    if(most_high_value<obj.profit)
    {
        best_sample = obj.sample;
        most_high_value = obj.profit;
    }
}
console.log("list_sample_profit.length:",list_sample_profit.length);
console.log("最大值:",most_high_value);
console.log("样本:",best_sample);

/*
最大值: 599
样本: [
   0,  1, -1,  1, -1, 1, -1,
   1, -1,  1, -1,  1, 0,  0,
  -1,  1, -1,  0
]
Contract SUCCESS - Gained $150.000m
*/

